package com.shiyipicture.shiyipicturebackend.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.shiyipicture.shiyipicturebackend.annotation.AuthCheck;
import com.shiyipicture.shiyipicturebackend.annotation.SaSpaceCheckPermission;
import com.shiyipicture.shiyipicturebackend.api.aliyun.AliYunAiApi;
import com.shiyipicture.shiyipicturebackend.api.aliyun.model.CreateOutPaintingTaskResponse;
import com.shiyipicture.shiyipicturebackend.api.aliyun.model.GetOutPaintingTaskResponse;
import com.shiyipicture.shiyipicturebackend.api.imageSearch.ImageSearchApiFacade;
import com.shiyipicture.shiyipicturebackend.api.imageSearch.model.ImageSearchResult;
import com.shiyipicture.shiyipicturebackend.auth.SpaceUserAuthManager;
import com.shiyipicture.shiyipicturebackend.auth.StpKit;
import com.shiyipicture.shiyipicturebackend.auth.constant.SpaceUserPermissionConstant;
import com.shiyipicture.shiyipicturebackend.common.BaseResponse;
import com.shiyipicture.shiyipicturebackend.common.DeleteRequest;
import com.shiyipicture.shiyipicturebackend.common.ResultUtils;
import com.shiyipicture.shiyipicturebackend.constant.UserConstant;
import com.shiyipicture.shiyipicturebackend.enums.PictureReviewStatusEnum;
import com.shiyipicture.shiyipicturebackend.enums.UserRoleEnum;
import com.shiyipicture.shiyipicturebackend.exception.BusinessException;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import com.shiyipicture.shiyipicturebackend.exception.ThrowUtils;
import com.shiyipicture.shiyipicturebackend.manager.cache.CacheTemplate;
import com.shiyipicture.shiyipicturebackend.manager.cache.CaffeineCacheStrategy;
import com.shiyipicture.shiyipicturebackend.manager.cache.RedisCacheStrategy;
import com.shiyipicture.shiyipicturebackend.manager.cache.TwoLevelCacheStrategy;
import com.shiyipicture.shiyipicturebackend.model.dto.picture.*;
import com.shiyipicture.shiyipicturebackend.model.entity.Picture;
import com.shiyipicture.shiyipicturebackend.model.entity.PictureTagCategory;
import com.shiyipicture.shiyipicturebackend.model.entity.Space;
import com.shiyipicture.shiyipicturebackend.model.entity.User;
import com.shiyipicture.shiyipicturebackend.model.vo.PictureVO;
import com.shiyipicture.shiyipicturebackend.service.PictureService;
import com.shiyipicture.shiyipicturebackend.service.SpaceService;
import com.shiyipicture.shiyipicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/picture")
public class PictureController {

  @Resource
  private UserService userService;

  @Resource
  private PictureService pictureService;

  @Resource
  private StringRedisTemplate stringRedisTemplate;

  @Resource
  private SpaceService spaceService;

  @Resource
  private AliYunAiApi aliYunAiApi;

  @Resource
  private SpaceUserAuthManager spaceUserAuthManager;

  /**
   * 构造caffeine本地缓存
   */
  private final Cache<String, String> LOCAL_CACHE =
    Caffeine.newBuilder().initialCapacity(1024)
      .maximumSize(10000L)
      // 缓存 5 分钟移除
      .expireAfterWrite(5L, TimeUnit.MINUTES)
      .build();


  /**
   * 上传图片
   *
   * @param multipartFile
   * @param pictureUploadRequest
   * @param request
   * @return 结果封装类图片vo
   */
  @PostMapping("/upload")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
  public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest, HttpServletRequest request) {
    User loginUser = userService.getLoginUser(request);
    PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
    return ResultUtils.success(pictureVO);
  }

  /**
   * 通过url上传图片
   *
   * @param pictureUploadRequest
   * @param request
   * @return 结果封装类图片vo
   */
  @PostMapping("/upload/url")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
  public BaseResponse<PictureVO> uploadPictureByUrl(PictureUploadRequest pictureUploadRequest, HttpServletRequest request) {
    User loginUser = userService.getLoginUser(request);
    String fileUrl = pictureUploadRequest.getFileUrl();
    PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
    return ResultUtils.success(pictureVO);
  }

  /**
   * 删除图片
   */
  @PostMapping("/delete")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
  public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
    ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
    User loginUser = userService.getLoginUser(request);
    Long id = deleteRequest.getId();
    boolean result = pictureService.deletePicture(id, loginUser);
    return ResultUtils.success(result);
  }

  /**
   * 更新图片（仅管理员可用）
   */
  @PostMapping("/update")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
  public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
    if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    Long spaceId = pictureUpdateRequest.getSpaceId();
    User loginUser = userService.getLoginUser(request);
    // 将实体类和 DTO 进行转换
    Picture picture = new Picture();
    BeanUtils.copyProperties(pictureUpdateRequest, picture);
    // 注意将 list 转为 string
    picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
    // 数据校验
    pictureService.validPicture(picture);
    // 判断是否存在
    Long pictureId = pictureUpdateRequest.getId();
    if (pictureId != null) {
      Picture oldPicture = pictureService.getById(pictureId);
      ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
      if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
        throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
      }
      if (spaceId != null) {
        ThrowUtils.throwIf(!spaceId.equals(oldPicture.getSpaceId()), ErrorCode.NO_AUTH_ERROR, "空间Id不一致");
      } else {
        if (oldPicture.getSpaceId() != null) {
          spaceId = oldPicture.getSpaceId();
        }
      }
    }
    picture.setSpaceId(spaceId);
    pictureService.fillReviewParams(picture, loginUser);
    // 操作数据库
    boolean result = pictureService.updateById(picture);
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    return ResultUtils.success(true);
  }

  /**
   * 根据 id 获取图片（仅管理员可用）
   */
  @GetMapping("/get")
  @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
  public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
    ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
    // 查询数据库
    Picture picture = pictureService.getById(id);
    ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
    // 获取封装类
    return ResultUtils.success(picture);
  }

  /**
   * 根据 id 获取图片（封装类）
   */
  @GetMapping("/get/vo")
  public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
    ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
    // 查询数据库
    Picture picture = pictureService.getById(id);
    ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
    Long spaceId = picture.getSpaceId();
    Space space = null;
    if (spaceId != null) {
      boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
      ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
      space = spaceService.getById(spaceId);
      ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
//      User loginUser = userService.getLoginUser(request);
//      pictureService.checkPictureAuth(loginUser, picture);
    }
    PictureVO pictureVO = pictureService.getPictureVO(picture, request);
    User loginUser = userService.getLoginUser(request);
    List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
    pictureVO.setPermissionList(permissionList);
    // 获取封装类
    return ResultUtils.success(pictureVO);
  }

  /**
   * 分页获取图片列表（仅管理员可用）
   */
  @PostMapping("/list/page")
  @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
  public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
    long current = pictureQueryRequest.getCurrent();
    long size = pictureQueryRequest.getPageSize();
    // 查询数据库
    Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
      pictureService.getQueryWrapper(pictureQueryRequest));
    return ResultUtils.success(picturePage);
  }

  /**
   * 分页获取图片列表（封装类）
   */
  @PostMapping("/list/page/vo")
  public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                           HttpServletRequest request) {
    long current = pictureQueryRequest.getCurrent();
    long size = pictureQueryRequest.getPageSize();
    Long spaceId = pictureQueryRequest.getSpaceId();
    if (spaceId == null) {
      pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
      pictureQueryRequest.setNullSpaceId(true);
    } else {
//      User loginUser = userService.getLoginUser(request);
//      Space space = spaceService.getById(spaceId);
//      ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//      if (!loginUser.getId().equals(space.getUserId())) {
//        throw new BusinessException(ErrorCode.NO_AUTH_ERROR, " 无权限");
//      }
      boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
      ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
    }
    // 限制爬虫
    ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
    pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
    // 查询数据库
    Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
      pictureService.getQueryWrapper(pictureQueryRequest));

    // 获取封装类
    return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
  }

  /**
   * 编辑图片（给用户使用）
   */
  @PostMapping("/edit")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
  public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
    if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    User loginUser = userService.getLoginUser(request);
    pictureService.editPicture(pictureEditRequest, loginUser);
    return ResultUtils.success(true);
  }

  /**
   * 标签获取
   *
   * @return
   */
  @GetMapping("/tag_category")
  public BaseResponse<PictureTagCategory> listPictureTagCategory() {
    PictureTagCategory pictureTagCategory = new PictureTagCategory();
    List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
    List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
    pictureTagCategory.setTagList(tagList);
    pictureTagCategory.setCategoryList(categoryList);
    return ResultUtils.success(pictureTagCategory);
  }

  /**
   * 审核图片
   *
   * @param pictureReviewRequest
   * @param request
   * @return
   */
  @PostMapping("/review")
  @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
  public BaseResponse<Boolean> doPictureReview(PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
    ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
    User loginUser = userService.getLoginUser(request);
    pictureService.doPictureReview(pictureReviewRequest, loginUser);
    return ResultUtils.success(true);
  }

  /**
   * 批量抓取图片
   *
   * @param pictureUploadByBatchRequest
   * @param request
   * @return
   */
  @PostMapping("/upload/batch")
  public BaseResponse<Integer> uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, HttpServletRequest request) {
    User loginUser = userService.getLoginUser(request);
    int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
    return ResultUtils.success(uploadCount);
  }

  /**
   * 分页获取图片列表（封装类）添加缓存
   */
  @PostMapping("/list/page/vo/cache")
  public BaseResponse<Page<PictureVO>> listPictureVOByPageCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                HttpServletRequest request) {
    long current = pictureQueryRequest.getCurrent();
    long size = pictureQueryRequest.getPageSize();
    // 限制爬虫
    ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
    pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
    String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
    String hasKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
    String redisKey = String.format("shiyipicture:listPictureVOByPage:%s", hasKey);
    String cacheKey = String.format("listPictureVOByPage:%s", hasKey);

    //缓存模板方法
    CacheTemplate cacheTemplate = new CacheTemplate(new TwoLevelCacheStrategy(stringRedisTemplate, LOCAL_CACHE));
    Page<PictureVO> cacheValue = cacheTemplate.execute(cacheKey, () -> {
      Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
        pictureService.getQueryWrapper(pictureQueryRequest));

      return pictureService.getPictureVOPage(picturePage, request);
    }, Page.class, 300 + RandomUtil.randomInt(0, 300), TimeUnit.SECONDS);
    return ResultUtils.success(cacheValue);
//    PictureCache pictureCache = new PictureCache();
//    Page<PictureVO> cacheValue = pictureCache.execute(redisKey, cacheKey, key -> {
//      Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
//        pictureService.getQueryWrapper(pictureQueryRequest));
//
//      return pictureService.getPictureVOPage(picturePage, request);
//    }, 300 + RandomUtil.randomInt(0, 300));
//    return ResultUtils.success(cacheValue);
//    //从本地缓存中查询数据
//    String cacheValueOfCaffeine = LOCAL_CACHE.getIfPresent(cacheKey);
//    if (cacheValueOfCaffeine != null) {
//      Page<PictureVO> cachedPage = JSONUtil.toBean(cacheValueOfCaffeine, Page.class);
//      return ResultUtils.success(cachedPage);
//    }
//    //从redis中查询数据
//    ValueOperations<String, String> stringValueOperations = stringRedisTemplate.opsForValue();
//    String cachedValue = stringValueOperations.get(redisKey);
//    if (cachedValue != null) {
//      Page<PictureVO> cachePage = JSONUtil.toBean(cachedValue, Page.class);
//      return ResultUtils.success(cachePage);
//    }
//    // 查询数据库
//    Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
//      pictureService.getQueryWrapper(pictureQueryRequest));
//
//    Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
//
//    //5-10分钟随机过期时间防止雪崩
//    int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);
//    String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
//    //存入caffeine
//    LOCAL_CACHE.put(cacheKey,cacheValue);
//    //存入redis
//    stringValueOperations.set(redisKey,cacheValue,cacheExpireTime, TimeUnit.SECONDS);
    // 获取封装类
//    return ResultUtils.success(pictureVOPage);
  }

  /**
   * 以图搜图
   */
  @PostMapping("/search/picture")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
  public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
    ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
    Long pictureId = searchPictureByPictureRequest.getPictureId();
    ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
    Picture picture = pictureService.getById(pictureId);
    ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
    List<ImageSearchResult> imageSearchResults = ImageSearchApiFacade.searchImage(picture.getUrl());
    return ResultUtils.success(imageSearchResults);
  }

  /**
   * 颜色搜索
   */
  @PostMapping("/search/color")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
  public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByPictureRequest, HttpServletRequest request) {
    ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
    Long spaceId = searchPictureByPictureRequest.getSpaceId();
    String picColor = searchPictureByPictureRequest.getPicColor();
    User loginUser = userService.getLoginUser(request);
    List<PictureVO> pictureVOS = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
    return ResultUtils.success(pictureVOS);
  }

  /**
   * 图片批量编辑
   */
  @PostMapping("/edit/batch")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
  public BaseResponse<Boolean> batchEdit(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
    ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
    User loginUser = userService.getLoginUser(request);
    pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
    return ResultUtils.success(true);
  }

  /**
   * 创建AI扩图任务
   */
  @PostMapping("/out_painting/create_task")
  @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
  public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, HttpServletRequest request) {
    ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null, ErrorCode.PARAMS_ERROR);
    User loginUser = userService.getLoginUser(request);
    return ResultUtils.success(pictureService.createOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser));
  }

  /**
   * 查询AI扩图任务
   */
  @GetMapping("/out_painting/get_task")
  public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
    ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
    return ResultUtils.success(aliYunAiApi.getOutPaintingTask(taskId));
  }
}
